package com.bdcom.component;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class DragableImgLabel extends JLabel{
	private DragableImgLabel thisLabel = this;
	private JPanel parentPanel = null;
	private String picPath = null;
	private int w = 0;
	private int h = 0;
	private BufferedImage bi = null;
	private boolean isSelected = false;
	private int posx = 10;
	private int posy = 10;
	
	public String labelPath = "";
	
	private boolean canReszie = true;
	
	public DragableImgLabel(JPanel p,String picPath){
		this.parentPanel = p;
		this.picPath = picPath;
		init();
	}

	public DragableImgLabel(JPanel p,String picPath,int w,int h){
		this.parentPanel = p;
		this.picPath = picPath;
		this.h = h;
		this.w = w;
		init();
	}
	
	public void init(){
		if(picPath!=null){
			try {
				bi = ImageIO.read(new File(picPath));
				if(w==0 && h==0){
					w = bi.getWidth();
					h = bi.getHeight();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		this.setBounds(posx, posy, w, h);
		MouseDragListener listener = new MouseDragListener(this);
		this.addMouseListener(listener);
		this.addMouseMotionListener(listener);
		this.addKeyListener(new MouseCtrlKeyListener(this));
	}
	
	protected void paintComponent(Graphics g) {
		if(bi != null){
			g.setColor(Color.red);
			g.fillRect(0, 0, w, h);
			g.drawImage(bi, 1, 1, w-2, h-2, null);
		}else{
			g.setColor(Color.green);
			g.fillRect(1, 1, w-2, h-2);
		}
		if(isSelected){
			g.setColor(Color.black);
			Graphics2D g2d = (Graphics2D)g;
			g2d.setStroke(new BasicStroke(1));
			g.drawRect(0, 0, w-1, h-1);
		}
	}
	
	public void setSelected(boolean flag){
		isSelected = flag ;
		this.repaint();
	}
	
	public boolean getIsSelected(){
		return isSelected;
	}

	public int getW() {
		return w;
	}

	public int getH() {
		return h;
	}

	public JPanel getParentPanel() {
		return parentPanel;
	}

	public void setParentPanel(JPanel parentPanel) {
		this.parentPanel = parentPanel;
	}
	
	public String getPicPath(){
		return picPath;
	}
	
	@Override
	public void setBounds(int i, int j, int k, int l) {
		super.setBounds(i, j, k, l);
		if(canReszie){
			this.w = k;
			this.h = l;
		}
	}
}
